package co.yixiang.modules.rotaryTable.rest;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.common.aop.NoRepeatSubmit;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.common.util.ToolUtil;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.modules.rotaryTable.domain.RotaryTable;
import co.yixiang.modules.rotaryTable.service.RotaryTableService;
import co.yixiang.modules.rotaryTable.service.dto.RotaryTableDto;
import co.yixiang.modules.rotaryTable.service.dto.RotaryTableQueryCriteria;
import co.yixiang.modules.rotaryTableRecord.domain.RotaryTableRecord;
import co.yixiang.modules.rotaryTableRecord.service.RotaryTableRecordService;
import co.yixiang.modules.rotaryTableRecord.service.dto.RotaryTableRecordQueryCriteria;
import co.yixiang.modules.user.domain.YxAuthentication;
import co.yixiang.modules.user.domain.YxUser;

import co.yixiang.modules.user.domain.YxUserAddress;
import co.yixiang.modules.user.service.YxAuthenticationService;
import co.yixiang.modules.user.service.YxUserAddressService;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@RestController
@Api(value = "转盘抽奖", tags = "抽奖:转盘抽奖", description = "转盘抽奖")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class YxRotarytableController {

    private final RotaryTableService rotaryTableService;
    private final RotaryTableRecordService rotaryTableRecordService;
    private final YxUserBillService billService;
    private final YxUserService yxUserService;
    private final YxUserAddressService yxUserAddressService;
    private final YxAuthenticationService yxAuthenticationService;

    /**
     *抽奖商品
     */
    @AuthCheck
    @GetMapping("/rotarytable/goods")
    @ApiOperation(value = "抽奖商品", notes = "抽奖商品")
    public ApiResult<Object> goods(){
        RotaryTableQueryCriteria rotaryTableDto = new RotaryTableQueryCriteria();
        List<RotaryTable> rotaryTableDtos = rotaryTableService.queryAll(rotaryTableDto);
        return ApiResult.ok(rotaryTableDtos);
    }


    /**
     *抽奖记录
     */
    @AuthCheck
    @GetMapping("/rotarytable/record")
    @ApiOperation(value = "抽奖记录", notes = "抽奖记录")
    public ApiResult<Object> record(@RequestParam(value = "page",defaultValue = "1") int page,
                                    @RequestParam(value = "limit",defaultValue = "10") int limit){
        YxUser yxUser= LocalUser.getUser();
        Long uid = yxUser.getUid();
        Page page1=new Page(page,limit);
//        RotaryTableRecordQueryCriteria rotaryTableRecordQueryCriteria = new RotaryTableRecordQueryCriteria();
//        rotaryTableRecordQueryCriteria.setUid(yxUser.getUid());
        Page<RotaryTableRecord> rotaryTableRecordsDtos = rotaryTableRecordService.queryAllPage(page1,uid);
        List <RotaryTableRecord> rotaryTableRecords = rotaryTableRecordsDtos.getRecords();
        for(RotaryTableRecord rotaryTableRecord:rotaryTableRecords){
            if(ObjectUtil.isNotEmpty(rotaryTableRecord.getUserAddress())){
                rotaryTableRecord.setStatus(1);
//                YxUserAddress yxUserAddress =  yxUserAddressService.getById(rotaryTableRecord.getUserAddress());
//                rotaryTableRecord.setUserAddress(yxUserAddress.getDetail());
            }
        }
        return ApiResult.ok(rotaryTableRecordsDtos);
    }

    /**
     *抽奖
     */
    @AuthCheck
    @GetMapping("/rotarytable/cost")
    @ApiOperation(value = "抽奖记录", notes = "抽奖记录")
    public ApiResult<Object> cost(){
        BigDecimal cost = new BigDecimal(rotaryTableService.getRotaryCost());
    return ApiResult.ok(cost);
    }


    /**
     * 抽奖扣除通宝
     */
    @AuthCheck
    @GetMapping("/rotarytable/draw")
    @NoRepeatSubmit
    @ApiOperation(value = "抽奖记录", notes = "抽奖记录")
    public ApiResult<Object> draw(){
        YxUser yxUser= LocalUser.getUser();
        YxAuthentication yxAuthentication = yxAuthenticationService.getOne(new QueryWrapper<YxAuthentication>().lambda()
                .eq(YxAuthentication::getUid , yxUser.getUid()));
        if(ObjectUtil.isEmpty(yxAuthentication)){
            throw new YshopException("未实名认证,不可参与抽奖");
        }
        BigDecimal integral = yxUser.getIntegral();
        BigDecimal cost = new BigDecimal(rotaryTableService.getRotaryCost());
        if(integral.compareTo(cost) == -1){
            throw new YshopException("通宝不足");
        }
        BigDecimal balance = integral.subtract(cost);

        //用户积分减少
        YxUser user = YxUser.builder()
                .integral(balance)
                .uid(yxUser.getUid())
                .build();
        boolean res = yxUserService.updateById(user);
        if(!res) throw new YshopException("抽奖失败");

        //插入流水
        billService.expend(yxUser.getUid(),"转盘抽奖", BillDetailEnum.CATEGORY_2.getValue(),
                BillDetailEnum.TYPE_12.getValue(),cost.doubleValue(),yxUser.getIntegral().doubleValue(),
                "");

        return ApiResult.ok("开始抽奖");
    }

    /**
     *录入记录
     */
    @AuthCheck
    @PostMapping("/rotarytable/inputInformation")
    @ApiOperation(value = "录入记录", notes = "录入记录")
    public ApiResult<Object> inputInformation(@Validated @RequestBody RotaryTableDto rotaryTable){
        YxUser yxUser= LocalUser.getUser();
       if(ObjectUtil.isNotEmpty(rotaryTable.getId())){
           if(ObjectUtil.isEmpty(rotaryTable.getUserAddress())){
               return ApiResult.ok("地址未填写");
           }
           YxUserAddress yxUserAddress =  yxUserAddressService.getById(rotaryTable.getUserAddress());
//           String address ="姓名："+ yxUserAddress.getRealName()+"手机号："+yxUserAddress.getProvince()
//                   +yxUserAddress.getCity()+yxUserAddress.getDistrict()+yxUserAddress.getDetail();
           RotaryTableRecord rotaryTableRecord =rotaryTableRecordService.getById(rotaryTable.getId());
           rotaryTableRecord.setUserAddress(rotaryTable.getUserAddress());
           rotaryTableRecordService.saveOrUpdate(rotaryTableRecord);
           return ApiResult.ok("地址填写成功");
       }
        RotaryTable rotaryTable1 = rotaryTableService.getById(rotaryTable.getRotaryId());
        RotaryTableRecord rotaryTableRecord = new RotaryTableRecord();
        rotaryTableRecord.setUid(yxUser.getUid());
        rotaryTableRecord.setName(rotaryTable1.getName());
        rotaryTableRecord.setStatus(0);
        rotaryTableRecord.setType(rotaryTable1.getType());
        rotaryTableRecordService.save(rotaryTableRecord);
        return ApiResult.ok("恭喜您已抽中奖品");
    }

    /**
     *抽奖
     */
    @AuthCheck
    @GetMapping("/rotarytable/randomWeight")
    @ApiOperation(value = "抽奖记录", notes = "抽奖记录")
    public ApiResult<Object> randomWeight(){
        RotaryTableQueryCriteria rotaryTableDto = new RotaryTableQueryCriteria();
        List<RotaryTable> rotaryTableDtos = rotaryTableService.queryAll(rotaryTableDto);
        List<Integer> weights =rotaryTableService.randomWeight();
        Integer id = random(weights);
        return ApiResult.ok(rotaryTableDtos.get(id));
    }

    public static int random(List<Integer> weight){
        List<Integer> weightTmp = new ArrayList<Integer>(weight.size()+1);
        weightTmp.add(0);
        Integer sum = 0;
        for( Integer d : weight ){
            sum += d;
            weightTmp.add(sum);
        }
        Random random = new Random();
        int rand = random.nextInt(sum);
        int index = 0;
        for(int i = weightTmp.size()-1; i >0; i--){
            if( rand >= weightTmp.get(i)){
                index = i;
                break;
            }
        }
        return index;
    }


}
